from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
from sqlalchemy.orm import sessionmaker
from models import *  # 引入 Base 和模型
import os
import configparser
import random
import aiohttp
import string
from aiohttp import web
import asyncio
import aiohttp_cors
import logging
import random
import string
import platform
import datetime


def load_config(config_path):
    config = configparser.ConfigParser()
    config.read(config_path,encoding='utf-8')
    return config

config_path = "config.ini"
config = load_config(config_path)


# 从配置文件中读取服务器配置
ZLK_HOST = config['setting']['ZLK_HOST']
ZLK_PORT = config['setting']['ZLK_PORT']
SE_RTSP = config.get('setting', 'SE_RTSP').format(ZLK_HOST=ZLK_HOST)
SE_RTMP = config.get('setting', 'SE_RTMP').format(ZLK_HOST=ZLK_HOST)
SE_VIDEO = config.get('setting', 'SE_VIDEO').format(ZLK_HOST=ZLK_HOST)
ZLK_SECRET = config['setting']['ZLK_SECRET']



# 读取数据库配置
DB_HOST = config['database']['DB_HOST']
DB_PORT = config['database']['DB_PORT']
DB_USER = config['database']['DB_USER']
DB_PASSWORD = config['database']['DB_PASSWORD']
DB_DATABASE = config['database']['DB_DATABASE']


# 构建数据库连接字符串
DATABASE_URL = f"mysql+aiomysql://{DB_USER}:{DB_PASSWORD}@{DB_HOST}:{DB_PORT}/{DB_DATABASE}"


# 创建异步 SQLAlchemy 引擎和会话
engine = create_async_engine(DATABASE_URL, echo=False, pool_recycle=3600)
AsyncSessionLocal = sessionmaker(
    bind=engine,
    class_=AsyncSession,
    expire_on_commit=False
)

# 在 aiohttp 应用中注册数据库生命周期
async def init_db(app):
    engine = create_async_engine(DATABASE_URL, echo=False)
    app['db_engine'] = engine
    app['db_sessionmaker'] = sessionmaker(
        bind=engine,
        expire_on_commit=False,
        class_=AsyncSession
    )

    # ✅ 自动建表
    async with engine.begin() as conn:
        await conn.run_sync(Base.metadata.create_all)

    yield
    await engine.dispose()


# 初始化数据库表结构
async def init_models():
    engine = create_async_engine(DATABASE_URL, echo=True)
    async with engine.begin() as conn:
        print("🔧 正在创建表...")
        await conn.run_sync(Base.metadata.create_all)
        print("✅ 表创建完成")
    await engine.dispose()


# 随机字符数字
def generate_mixed_id(length=40):
    if length < 3:
        raise ValueError("长度至少为3，才能保证包含大小写字母和数字")
    upper = random.choice(string.ascii_uppercase)
    lower = random.choice(string.ascii_lowercase)
    digit = random.choice(string.digits)
    others = random.choices(string.ascii_letters + string.digits, k=length - 3)
    combined = [upper, lower, digit] + others
    random.shuffle(combined)
    return ''.join(combined)



# if __name__ == "__main__":
#     asyncio.run(init_models())

